import uuid

from rest_framework import status
import pandas as pd
from rest_framework.response import Response

from fasu.models import DisposalSubjectModel, CaseInfoModel, FileModel, PrincipalModel, MediationModel, PartModel, \
    BatchModel, CourtsModel

from fasu.serializers import DisposalSubjectModelSerializer, DisposalSubjectModelCreateUpdateSerializer, \
    CaseInfoModelSerializer, CaseInfoModelCreateUpdateSerializer, FileSerializer, PrincipalModelSerializer, \
    PrincipalModelCreateUpdateSerializer, MediationModelSerializer, MediationModelCreateUpdateSerializer, \
    PartModelSerializer, PartModelCreateUpdateSerializer, \
    BatchModelSerializer, BatchModelCreateUpdateSerializer

# 导入文件专属使用
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.viewsets import mixins, GenericViewSet


def upload(file_object, depart, company):
    """分案表导入"""
    df = pd.read_excel(file_object)
    # 分案表导入数据表格
    key_list = [
        "hand_parting", "commission_batch", "commission_area", "blk", "commission_start_time",
        "commission_end_time", "remark", "case_no", "contract_no", "principal_amount",
        "total_amount", "total_amount_min", "total_amount_min_dollar", "entry_reminder_date",
        "account_opening_date",
        "card_suspension_day", "name", "gender", "id_no", "phone",
        "date_of_birth", "residence_add", "disposal_subject", "nation", "application",
    ]

    value_list = [
        '手别', '委托批次', '委外大区', 'BLK', '委外起始日期',
        '委外计划截止日期', '客户号', '真账号', '首张激活卡号', '账户余额本金',
        '人民币余额', '人民币最低应缴款金额', '美元最低应缴款金额', '入催日', '开户日',
        '停卡日', '客户名称', '客户性别', '证件号码', '客户手机号码',
        '出生日期', '户籍地址', '处置主体', '民族', '申请单日',
    ]

    z = dict(zip(key_list, value_list))

    for rows in df.itertuples():
        value2_list = []
        # 委案批次自增———
        a = not BatchModel.objects.filter(casebatch=str(getattr(rows, '委托批次'))).exists()
        if a:
            BatchModel.objects.create(
                **{
                    "uuid": str(uuid.uuid4()),
                    "casebatch": str(getattr(rows, '委托批次')),
                    "company_id": PrincipalModel.objects.get(id=int(company))
                }
            )

        for k, v in z.items():
            value2_list.append(str(getattr(rows, v)).replace('\n', ''))
        print(value2_list)
        dic_object = dict(zip(key_list, value2_list))
        print(dic_object)
        id_no = str(getattr(rows, '证件号码'))
        md_object = CaseInfoModel.objects.filter(id_no=id_no)   # 判断案件列表中是否存在
        dic_object.update({
            "depart": DisposalSubjectModel.objects.get(id=int(depart)),
            "commission_company": PrincipalModel.objects.get(id=int(company)),
        })
        if len(md_object) > 0:
            md_object.update(**dic_object)
        else:
            CaseInfoModel.objects.create(**dic_object)
    return '导入完成!!!'


def upload_interest(file_object, depart, company):
    """本息表数据导入"""

    df = pd.read_excel(file_object, dtype="str")
    interest_key_list = [
        "data_time", "amount_owed", "principal",
        "interest", "default_money", "annual_fee",
        "installment_handling_fee", "other_expenses",
    ]
    interest_value_list = [
        "取数日期", "欠款总额", "本金",
        "利息", "违约金", "年费",
        "分期手续费", "其他费用"
    ]

    z = dict(zip(interest_key_list, interest_value_list))
    z.update({
        "depart": depart,
        'company': company
    })
    for rows in df.itertuples():
        value2_list = []  # 获取表格对应值——已列表形式 # 需要拼接字典
        id_no = str(getattr(rows, '身份证'))
        for k, v in z.items():
            value2_list.append(str(getattr(rows, v)))
        dic_object = dict(zip(interest_key_list, value2_list))
        md_object = CaseInfoModel.objects.filter(id_no=id_no)
        if len(md_object) > 0:
            md_object.update(**dic_object)  # 只更新已存在数据
        # else:
        #     CaseInfoModel.objects.create(**dic_object)  # 写入数据库
    return "更新完成！！！"


# 文件上传 <主体代码subject，委案公司代码company>
class FileViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, GenericViewSet):
    queryset = FileModel.objects.all()
    serializer_class = FileSerializer

    # 重写更新方法
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        if '分案表' == request.data.get('name'):
            object = upload(
                request.FILES.get('file'),
                request.data.get('subject'),
                request.data.get('company'),
                request.data.get('company'),
                request.data.get('company'),
            )
        else:
            object = upload_interest(
                request.FILES.get('file'),
                request.data.get('subject'),
                request.data.get('company')
            )

        object_end = serializer.data
        object_end.update({
            "data": object
        })
        return Response(object_end, status=status.HTTP_201_CREATED, headers=headers)


class DisposalSubjectModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = DisposalSubjectModel.objects.all()
    serializer_class = DisposalSubjectModelSerializer
    create_serializer_class = DisposalSubjectModelCreateUpdateSerializer
    update_serializer_class = DisposalSubjectModelCreateUpdateSerializer
    # 导入序列化器
    import_serializer_class = DisposalSubjectModelSerializer
    # 导入配置
    import_field_dict = {
        "disposal_subject_id": {
            "title": "处置主体id",
            "display": "disposal_subject_id",
            # "choices": {
            #     "data": {"启用": 1, "禁用": 0},
            # }
        },
        "disposal_subject_name": "名称",
        'create_datetime': {
            "title": '处置主体名称',
            "display": 'disposal_subject_name',
            # "type": "date"
        },
        "disposal_subject_code": {
            "title": "处置主体代码",
            "display": 'disposal_subject_code',
            # "choices": {
            #     "queryset": Dept.objects.values('name'),
            #     "values_name": "name"
            # }
        },
        "watermark_data": "盖章水印参数"
    }


class CaseInfoModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = CaseInfoModel.objects.all()
    serializer_class = CaseInfoModelSerializer
    create_serializer_class = CaseInfoModelCreateUpdateSerializer
    update_serializer_class = CaseInfoModelCreateUpdateSerializer


class PrincipalModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = PrincipalModel.objects.all()
    serializer_class = PrincipalModelSerializer
    create_serializer_class = PrincipalModelCreateUpdateSerializer
    update_serializer_class = PrincipalModelCreateUpdateSerializer


class MediationModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = MediationModel.objects.all()
    serializer_class = MediationModelSerializer
    create_serializer_class = MediationModelCreateUpdateSerializer
    update_serializer_class = MediationModelCreateUpdateSerializer


class PartModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = PartModel.objects.all()
    serializer_class = PartModelSerializer
    create_serializer_class = PartModelCreateUpdateSerializer
    update_serializer_class = PartModelCreateUpdateSerializer


class BatchModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = BatchModel.objects.all()
    serializer_class = BatchModelSerializer
    create_serializer_class = BatchModelCreateUpdateSerializer
    update_serializer_class = BatchModelCreateUpdateSerializer





from fasu.serializers import CourtsModelSerializer, CourtsModelCreateUpdateSerializer

class CourtsModelViewSet(CustomModelViewSet):
    """"""
    queryset = CourtsModel.objects.all()
    serializer_class = CourtsModelSerializer
    create_serializer_class = CourtsModelCreateUpdateSerializer
    update_serializer_class = CourtsModelCreateUpdateSerializer
